package com.contract.management.web;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.contract.management.domain.CommJpaRepository;
import com.contract.management.domain.User;

public class SecurityInterceptor implements HandlerInterceptor {

	private static final Map<Integer, String> RIGHT = new HashMap<Integer, String>() {{
		put(1, "/|^/index|^/audit/.*|^/contract/.*|");
		put(2, get(1));
		put(3, get(1));
		put(4, get(1));
		put(5, "/|^/index|^/apply/.*|^/contract/.*|");
		
	}};
	
	private static final String NORIGHT = "/error|^/noright|^/user/password|^/logout|^/download/pdf/.*|^/api/.*";
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) 
			throws Exception {
		String url = request.getServletPath();
		if(url.matches(NORIGHT)) return true;
		
		if(!authentication(request, response)) {
			String context = request.getContextPath();
			String query = request.getQueryString();
			String rurl = request.getServletPath() + (query == null ? "" : "?" + query);
			if("/".equals(rurl)) {
				response.sendRedirect(context + "/login");
			} else {
				response.sendRedirect(context + "/login?redirect=" + rurl);
			}
			return false;
		} else if(!authorization(request, response)) {
			String context = request.getContextPath();
			response.sendRedirect(context + "/noright");
			return false;
		}
		return true;
	}
	
	//认证
	private boolean authentication(HttpServletRequest request, HttpServletResponse response) {
		
		//开发用，重启后自动登录
		if(request.getSession().getAttribute("user") != null) {
			User user = (User)request.getSession().getAttribute("user");
			Cookie cookie = new Cookie("user", String.valueOf(user.getId()));
			response.addCookie(cookie);
		} else if(request.getCookies() != null) {
			for (Cookie	cookie : request.getCookies()) {
				if(cookie.getName().equals("user")) {
					WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext()); 
					CommJpaRepository repo = ctx.getBean(CommJpaRepository.class);
					User user = repo.find(User.class, Integer.valueOf(cookie.getValue()));
					if("admin".equals(user.getUsername())) {
						user.setRight(6);	
					} else {
						user.setRight(user.getDept().getRight().getId());
					}
					
					request.getSession().setAttribute("user", user);
				}
			}
		}
		return request.getSession().getAttribute("user") != null;
	}

	//授权
	private boolean authorization(HttpServletRequest request, HttpServletResponse response) {
		
		Integer right = (Integer)request.getSession().getAttribute("right");
		//return url.matches(RIGHT.get(u.getDept().getRight().getId()));
		return true;
	}

	private boolean isRestful(Object handler) {
		if(!(handler instanceof HandlerMethod)) return false;
		
		HandlerMethod method = (HandlerMethod)handler;
		ResponseBody body = method.getMethodAnnotation(ResponseBody.class);
		if(body != null) return true;
		RestController rest = method.getBeanType().getAnnotation(RestController.class);
		if(rest != null) return true;
		return false;
	}
	
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

}
